package com.app.micaihu.view.home.arms.fragment

import android.content.Intent
import android.util.TypedValue
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.GridLayoutManager
import com.app.base.BaseMvpFragment
import com.app.http.bean.BaseBean
import com.app.micaihu.R
import com.app.micaihu.view.bean.Arms
import com.app.micaihu.configure.Config
import com.app.micaihu.configure.LoadType
import com.app.micaihu.configure.UmEventId
import com.app.micaihu.utils.MobclickAgentUtils
import com.app.micaihu.view.home.arms.adapter.ArmsListAdapter
import com.app.micaihu.view.home.arms.contract.ArmsContract
import com.app.micaihu.view.home.arms.presenter.ArmsPresenter
import com.app.micaihu.view.camera.activity.CameraActivity
import com.app.micaihu.view.camera.utils.DialogUtils
import com.app.micaihu.view.user.userinfo.activity.WebActivity
import com.blankj.utilcode.constant.PermissionConstants
import com.blankj.utilcode.util.*
import com.blankj.utilcode.util.PermissionUtils.FullCallback
import com.blankj.utilcode.util.PermissionUtils.OnRationaleListener.ShouldRequest
import kotlinx.android.synthetic.main.main_arms_list.*

/**
 * 武器库
 */
class ArmsListFragment : BaseMvpFragment<ArmsContract.View, ArmsPresenter>(), ArmsContract.View {

    override fun getLayoutId() = R.layout.main_arms_list
    override fun getPresenter() = ArmsPresenter()

    private val armsListAdapter: ArmsListAdapter by lazy {
        ArmsListAdapter()
    }
    private val linearLayoutManager by lazy {
        GridLayoutManager(context, 2)
    }
    private val footerView by lazy {
        layoutInflater.inflate(R.layout.view_empty_view, rvArms, false)
    }

    override fun setData() {
        rvArms.layoutManager = linearLayoutManager
        rvArms.adapter = armsListAdapter
        footerView.setPadding(0, SizeUtils.dp2px(50f), 0, 0)
        val textView = footerView.findViewById<TextView>(R.id.tvEmptyView)
        textView.text = "更多精彩,敬请期待..."
        textView.setTextColor(ColorUtils.getColor(R.color.colorB1B1B1))
        textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14f)
        armsListAdapter.addFooterView(footerView)
        val layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, BarUtils.getStatusBarHeight() + SizeUtils.dp2px(44f))
        rlTitle.layoutParams = layoutParams
    }

    override fun lazyLoad() {
        armsListAdapter.setEmptyView(loadingView)
        mPresenter?.arms()
    }

    override fun addListeners() {
        refreshLayout.setOnRefreshListener {
            mPresenter?.arms()
        }
        armsListAdapter.setOnItemClickListener { adapter, view, position ->
            val item = armsListAdapter.getItem(position)
            if (Config.MenuType.isH5 == item.type) {
                if (item.url.isNotEmpty()) {
                    val intent = Intent(activity, WebActivity::class.java)
                    intent.putExtra(Config.Extra.url, item.url)
                    startActivity(intent)
                }
            } else if (Config.MenuType.isOriginal == item.type) {
                requestPermission()
            }

            when (item.title) {
                "战术望远镜" -> {
                    MobclickAgentUtils.event(UmEventId.tool_telescope, "工具-战术望远镜")
                }
                "军力排行榜" -> {
                    MobclickAgentUtils.event(UmEventId.tool_militrayrank, "工具-军力排行榜")
                }
                "前世今生" -> {
                    MobclickAgentUtils.event(UmEventId.tool_infrontlife, "工具-前世今生")
                }
                "历史上的今天" -> {
                    MobclickAgentUtils.event(UmEventId.tool_today, "工具-历史上的今天")
                }

            }
        }
    }

    override fun handleArms(arms: BaseBean<Arms?>?, loadType: Int) {
        refreshLayout.finishRefresh(Config.delayRefresh)
        if (arms == null) {
            armsListAdapter.removeFooterView(footerView)
            if (armsListAdapter.data.isNotEmpty()) {
                if (LoadType.TYPE_REFRESH_ERROR == loadType) {
                    ToastUtils.showShort(R.string.empty_network_error)
                }
            } else {
                if (LoadType.TYPE_REFRESH_ERROR == loadType) {
                    armsListAdapter.setEmptyView(errorView)
                }
            }
        } else {
            if (arms.isSuccess()) {
                arms.data?.let {
                    if (it.buttonList.isEmpty()) {
                        armsListAdapter.removeFooterView(footerView)
                    } else {
                        armsListAdapter.setNewInstance(it.buttonList.toMutableList())
                    }
                }
            }
        }
    }

    private fun requestPermission() {
        PermissionUtils.permission(PermissionConstants.CAMERA)
                .rationale { activity: UtilsTransActivity?, shouldRequest: ShouldRequest ->
                    //拒接后的回调
                    shouldRequest.again(true)
                }.callback(object : FullCallback {
                    override fun onGranted(permissionsGranted: List<String>) {
                        val intent = Intent(context, CameraActivity::class.java)
                        startActivity(intent)
                    }

                    override fun onDenied(permissionsDeniedForever: List<String>, permissionsDenied: List<String>) {
                        if (CollectionUtils.isNotEmpty(permissionsDeniedForever)) { // 永不访问
                            DialogUtils.showOpenAppSettingDialog({ dialog, which ->
                                dialog.dismiss()
                                PermissionUtils.launchAppDetailsSettings()
                            }) { dialog, which -> dialog.dismiss() }
                        } else if (CollectionUtils.isNotEmpty(permissionsDenied)) {
                            DialogUtils.showRationaleDialog({ dialog, which -> requestPermission() }) { dialog, which -> dialog.dismiss() }
                        }
                    }
                }).request()
    }
}